package com.pro.schedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.schedule.entity.Memo;
import com.pro.schedule.filter.ResultUtil;
import com.pro.schedule.mapper.MemoMapper;
import com.pro.schedule.service.MemoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;

@Service
public class MemoServiceImpl implements MemoService {
    @Resource
    ResultUtil resultUtil;
    @Resource
    MemoMapper memoMapper;

    @Override
    public IPage<Memo> getMemoIPage(String token, Page<Memo> page, LocalDate memoDate) {
        Long userId = resultUtil.getUserId(token);
        IPage<Memo> MemoIPage = memoMapper.selectMemoByUserId(page, userId, memoDate);
        for (Memo item : MemoIPage.getRecords()) {
            item.setUserId(0L);
        }
        return MemoIPage;
    }

    @Override
    public String saveOrUpdateMemo(String token, Memo memo) throws Exception {
        Long userId = resultUtil.getUserId(token);
        memo.setUserId(userId);
        if (memo.getMemoId() == null) {
            int result = memoMapper.insert(memo);
            return resultUtil.getResult(result, "保存");
        } else {
            int result = memoMapper.updateById(memo);
            return resultUtil.getResult(result, "修改");
        }
    }

    @Override
    public String deleteMemo(Integer memoId) throws Exception {
        int result = memoMapper.deleteById(memoId);
        return resultUtil.getResult(result, "删除");
    }

    @Override
    public int getMemoCount(String token) {
        Long userId = resultUtil.getUserId(token);
        QueryWrapper<Memo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("memo_date", LocalDate.now());
        return memoMapper.selectCount(wrapper);
    }
}
